<?php

/**
 * 积分兑换
 * File Name：RedeemModel.php
 * File Encoding：UTF-8
 * File New Time：2014-6-14 9:39:53
 * Author：水平凡
 * Mailbox：admin@abc3210.com
 */
class RedeemModel extends BaseModel {

    const STATUS_NOT = 0;  //未审核
    const STATUS_APPROVE = 1; //审核通过
    const STATUS_REJECT = 2; //审核被拒绝
    const STATUS_CANCEL = 3; //用户取消

    /*    const REFUND_NOT = 0; //未退款  
      const REFUND_HAS = 1;//已付款

      const PAYMENT_NOT = 0;//未付款
      const PAYMENT_HAS = 1;//已付款 */
    CONST PAY_STATUS_NOT = 0;  //未付款
    CONST PAY_STATUS_HAS = 1;  //已付款
    CONST PAY_STATUS_REFUND_NOT = 2;  //准备进行退款
    CONST PAY_STATUS_REFUND_HAS = 3; //已退款

    public function tableName() {
        return '{{redeem}}';
    }

    public function rules() {
        return array(
            array('title', 'required', 'message' => '商品标题不能为空！'),
            array('thumb', 'required', 'message' => '商品缩图不能为空！'),
            array('worth', 'required', 'message' => '商品价值不能为空！'),
            array('integral', 'required', 'message' => '商品兑换积分不能为空！'),
            array('member_group', 'required', 'message' => '允许兑换的会员组不能为空！'),
            array('start_time', 'required', 'message' => '商品兑换开始时间不能为空！'),
            //array('end_time', 'required', 'message' => '商品兑换结束时间不能为空！'),
            array('uid', 'required'),
            //无需检查
            array('introduction,status,admin_id,add_time,listorder,pay_status,exchange_start_time', 'safe'),
            array('url,quantum,frequency,product_id,commission', 'required'),
            array('thumb,url', 'checkUrl'),
            array('worth,commission', 'numerical', 'allowEmpty' => false),
            array('scoregood_intervals', 'numerical', 'allowEmpty' => true, 'integerOnly' => true),
            array('integral,quantum,frequency', 'numerical', 'integerOnly' => true, 'allowEmpty' => false),
            //array('quantum', 'numerical', 'integerOnly' => true, 'min' => 5),//NODE取消最少的限制
        );
    }

    public function checkUrl() {
        if (stripos($this->url, 'http://', 0) !== 0) {
            $this->addError('url', '商品地址不符合规范');
            return false;
        }

        if (!((stripos($this->url, '.tmall.com/', 0) != false) || (stripos($this->url, '.taobao.com/', 0) != false))) {
            $this->addError('url', '商品地址不符合规范,需要淘宝链接');
            return false;
        }


        if (stripos($this->thumb, 'http://', 0) !== 0) {
            $this->addError('thumb', '缩略图地址不符合规范');
            return false;
        }
    }

    public function relations() {
        return array(
            'MembersModel' => array(self::BELONGS_TO, 'MembersModel', 'uid',),
            'MembersTaobaoModel' => array(self::BELONGS_TO, 'MembersTaobaoModel', 'uid',),
            'RedeemRecordsModel' => array(self::HAS_MANY, 'RedeemRecordsModel', 'redeem_id'),
            'MoneyPositionOrderModel' => array(self::HAS_ONE, 'MoneyPositionOrderModel', 'goods_bm_id', 'condition' => 'MoneyPositionOrderModel.payment_types = 8'),
        );
    }

    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    public function add($data = '') {
        if (empty($data)) {
            $data = $_POST;
        }
        if (is_array($data['member_group'])) {
            $data['member_group'] = implode(',', $data['member_group']);
        }
        $this->attributes = $data;
        $this->setIsNewRecord(true);
        if ($this->validate() && $this->save()) {
            return true;
        } else {
            return false;
        }
    }

    public function editor($data) {
        if (empty($data)) {
            $this->addError('', '没有修改数据！');
            return false;
        }
        $model = $this->findByPk($data['id']);
        if (empty($model)) {
            $this->addError('', '该信息不存在！');
            return false;
        }
        if (is_array($data['member_group'])) {
            $data['member_group'] = implode(',', $data['member_group']);
        }
        if (!empty($data['start_time'])) {
            $data['start_time'] = strtotime($data['start_time']);
        }
        if (!empty($data['end_time'])) {
            $data['end_time'] = strtotime($data['end_time']);
        }
        if (!empty($data['exchange_start_time'])) {
            $data['exchange_start_time'] = strtotime($data['exchange_start_time']);
        }

        //$model->attributes = $data;
        foreach ($data as $key => $strData) {
            if ($key == 'id') {
                continue;
            }
            $model->$key = $strData;
        }
        if ($model->validate() && $model->save()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取当前商品已兑换次数
     * @param type $id
     * @param type $cache
     * @return type
     */
    public function getRecordQuantum($cache = false) {
        $key = "RedeemModel_getQuantums_{$this->id}";
        //如果是布尔值true，进行缓存更新
        if ((is_bool($cache) && $cache == true) || is_null($cache)) {
            Yii::app()->cache->delete($key);
            //return true;
        }
        $cache = Yii::app()->cache->get($key);
        if (empty($cache)) {
            $cache = RedeemRecordsModel::model()->getRedeemSum($this->id);
            //进行永久性缓存
            Yii::app()->cache->set($key, $cache, 300);
        }
        return $cache;
    }

    //数据保存前操作
    protected function beforeSave() {
        //时间处理
        if (!is_numeric($this->start_time)) {
            $this->start_time = strtotime($this->start_time);
        }
        if (!is_numeric($this->end_time)) {
            $this->end_time = strtotime($this->end_time);
        }
        if (!is_numeric($this->exchange_start_time)) {
            $this->exchange_start_time = strtotime($this->exchange_start_time);
        }

        //是否新增
        if ($this->isNewRecord) {
            //添加时间
            $this->add_time = time();
            //$this->end_time = $this->start_time + 86400*365;
            if (!empty(Yii::app()->passport)) {
                $this->admin_id = Yii::app()->passport['admin_id'];
            }
        } else {
            
        }
        return true;
    }

    public function createSearchCriteria() {
        $criteria = new CDbCriteria;

        $criteria->compare('id', $this->id);
        $criteria->compare('uid', $this->uid);
        $criteria->compare('title', $this->title, true);
        $criteria->compare('status', $this->status);
        $criteria->compare('pay_status', $this->pay_status);
        $criteria->compare('product_id', $this->product_id);

        if (!empty($this->start_time)) {
            $start_time = strtotime($this->start_time);
            $criteria->addCondition('start_time >= :start_time ');
            $criteria->params['start_time'] = $start_time;
        }

        if (!empty($this->end_time)) {
            $end_time = strtotime($this->end_time);
            $criteria->addCondition('end_time <= :end_time ');
            $criteria->params['end_time'] = $end_time;
        }


        return $criteria;
    }

    public static function getStatusHtmlDetail($intStatus) {
        $arrData = self::getStatusHtmlList();
        return $arrData[$intStatus];
    }

    public static function getStatusHtmlList() {
        return array(
            self::STATUS_NOT => '未审核',
            self::STATUS_APPROVE => '通过审核',
            self::STATUS_REJECT => '审核被拒绝',
            self::STATUS_CANCEL => '用户已取消',
        );
    }

    public static function getPayStatusHtmlDetail($intStatus) {
        $arrData = self::getPayStatusHtmlList();
        return $arrData[$intStatus];
    }

    public static function getPayStatusHtmlList() {
        return array(
            self::PAY_STATUS_NOT => '未付款',
            self::PAY_STATUS_HAS => '已付款',
            self::PAY_STATUS_REFUND_NOT => '准备进行退款',
            self::PAY_STATUS_REFUND_HAS => '已退款',
        );
    }

    public function getOperationHtml() {
        $action = array();
        $action[] = array(
            'url' => Yii::app()->createUrl('user/redeemgood/view', array('id' => $this->id)),
            'html' => '详情',
        );
        if ($this->status != self::STATUS_NOT) {
            //已受理,不能做其它操作
        } else {
            $action[] = array(
                'url' => Yii::app()->createUrl('user/redeemgood/cancel', array('id' => $this->id)),
                'html' => '取消报名',
            );
            if ($this->pay_status == self::PAY_STATUS_NOT) {
                //未付款
                $action[] = array(
                    'url' => Yii::app()->createUrl('user/redeemgood/pay', array('id' => $this->id)),
                    'html' => '去付款',
                );
                $action[] = array(
                    'url' => Yii::app()->createUrl('user/redeemgood/edit', array('id' => $this->id)),
                    'html' => '编辑修改',
                );
            }
        }
        return $action;
    }

    public function attributeLabels() {
        return array(
            'title' => '商品标题',
            'url' => '商品地址',
            'thumb' => '缩略图',
            'worth' => '价格',
            'integral' => '所需积分',
            'quantum' => '兑换商品个数',
            'frequency' => '允许兑换次数',
            'member_group' => '允许会员组',
            'start_time' => '开始时间',
            'end_time' => '结束时间',
            'listorder' => '排序',
            //'is_payment' => '是否支付',
            'product_id' => '产品ID',
            'introduction' => '商品介绍',
            'status' => '状态',
            'commission' => '佣金百分比',
            'add_time' => '创建时间',
            //'paymoney' => '支付金额',
            'pay_status' => '付款状态',
            'scoregood_intervals' => '购买间隔时间',
        );
    }

    /**
     * 未开始受理的时候可以执行取消操作
     * @return [type] [description]
     */
    public function canCancel() {
        if ($this->status == self::STATUS_NOT) {
            return true;
        }
        return false;
    }

    /**
     * 未开始受理与未支付的时候才可以执行修改操作
     * @return [type] [description]
     */
    public function canUpdate() {
        if ($this->status == self::STATUS_NOT) {
            if ($this->pay_status == self::PAY_STATUS_NOT) {
                return true;
            }
        }
        return false;
    }

    public function doExchange($userInfo = '') {

        empty($userInfo) ? $userInfo = Yii::app()->user->getInfo() : '';

        if ($userInfo['kind'] != 1) {
            return array(
                'error' => '只允许买家会员参与活动！',
                'url' => yii::app()->createUrl('/user/info'),
                'error_code' => 1106,
            );
        }
        if ($this->exchange_start_time >= time()) {
            return array(
                'error' => '还没有到兑换开始时间，开始时间：' . date('Y-m-d H:i:s', $this->exchange_start_time),
                'error_code' => 1108,
            );
        }
        //这是真正的展示的时间了
        
        if ($this->start_time > time()) {
            return array(
                'error' => '还没有到兑换开始时间，开始时间：' . date('Y-m-d H:i:s', $this->start_time),
                'error_code' => 1108,
            );
        }
        
        if ($this->end_time && $this->end_time < time()) {
            return array(
                'error' => '该商品兑换时间已经结束，结束时间：' . date('Y-m-d H:i:s', $this->end_time),
                'error_code' => 1109,
            );
        }
        if ($this->status != self::STATUS_APPROVE) {
            return array(
                'error' => '未通过审核或已取消',
                'error_code' => 1110,
            );
        }


        //只要有存在这今天兑换的记录未取消的就不能再兑换了
//        $intStartTime = strtotime('today');
//        $intEndTime = time();
//        $objCDbCriteria = new CDbCriteria(array(
//            'condition' => 'uid = :uid AND record_time >= :starttime AND record_time <= :endtime and is_sure != :is_sure',
//            'params' => array('uid' => yii::app()->user->id, 'starttime' => $intStartTime, 'endtime' => $intEndTime, 'is_sure' => RedeemRecordsModel::SURE_CANCEL),
//        ));
//
//        if(RedeemRecordsModel::model()->find($objCDbCriteria))
//        {
//            $this->addError('', "每个人每天只能兑换一次,你已兑换过");
//            return false;            
//        }
        //只能间隔的时间,,查询最近的一次兑换记录
        $arrData = array(
            'condition' => 'redeem_id = :redeem_id and is_sure != :is_sure',
            'params' => array('redeem_id' => $this->id, 'is_sure' => RedeemRecordsModel::SURE_CANCEL),
            'order' => 'record_time desc',
        );
        $objRecord = RedeemRecordsModel::model()->find($arrData);

        $intervals = $this->scoregood_intervals;

        $date_before = date('Y-m-d H:i', $objRecord->record_time); //上次兑换的时间
        $date_can = date('Y-m-d H:i', $objRecord->record_time + $intervals * 60);    //允许兑换的时间


        if ($objRecord) {
            if ((time() - $objRecord->record_time) < $intervals * 60) {
                return array(
                    'error' => "亲,该产品{$intervals}分钟兑换一次，上一次此商品兑换的时间是{$date_before},下次兑换时间为{$date_can}",
                    'error_code' => 1115,
                );
            }
        }



        //兑换次数
//        if ($this->frequency && RedeemRecordsModel::model()->getUserRedeemSum(yii::app()->user->uid, $this->id) >= $this->frequency) {
//            $this->addError('', "每个人最多允许兑换{$this->frequency}次！");
//            return false;
//        }
        if ($this->frequency && RedeemRecordsModel::model()->getUserRedeemSum($userInfo['uid'], $this->id) >= 1) {
            return array(
                'error' => "您已经兑换了该商品，不能再兑换了。请兑换其他商品！",
                'error_code' => 1111,
            );
        }

        $member_group = explode(',', $this->member_group);
        if (!in_array($userInfo['group_id'], $member_group)) {
            return array(
                'error' => "您所在的会员组没有兑换该商品的权限！",
                'error_code' => 1112,
            );            
        }
        //限量
        $quantum = $this->getRecordQuantum();
        if ($this->quantum && $quantum >= $this->quantum) {
            return array(
                'error' => "该商品已经兑换完，请兑换其他商品！",
                'error_code' => 1113,
            );            
        }
        //先扣积分在兑换
        if (MembersModel::model()->deductionScore($userInfo['uid'], $this->integral) !== true) {
            return array(
                'error' => MembersModel::model()->getOneError(),
                'error_code' => 1117,
            );            
        }

        MembersActionModel::model()->addRedeemAction($userInfo['uid'], "兑换商品 {$this->title} ID:{$this->id} 扣除积分 {$this->integral} ");
        //增加兑换记录
        RedeemRecordsModel::model()->addLogs($this, $userInfo);

        //更新缓存
        $quantum = $this->getRecordQuantum(true);
        if (($this->quantum - $quantum) <= 0) {
            //改只三天的时间就下架了
            $this->end_time = time() + 86400 * 3;
            $this->save(false, array('end_time'));
        }
        return true;
    }

    public function is_begin() {
        //判断间隔的时间
        $arrData = array(
            'condition' => 'redeem_id = :redeem_id and is_sure != :is_sure',
            'params' => array('redeem_id' => $this->id, 'is_sure' => RedeemRecordsModel::SURE_CANCEL),
            'order' => 'record_time desc',
        );
        $objRecord = RedeemRecordsModel::model()->find($arrData);

        $intervals = $this->scoregood_intervals;

        $date_before = date('Y-m-d H:i', $objRecord->record_time); //上次兑换的时间
        $date_can = date('Y-m-d H:i', $objRecord->record_time + $intervals * 60);    //允许兑换的时间


        if ($objRecord) {
            if ((time() - $objRecord->record_time) < $intervals * 60) {
                $this->addError('', "亲,该产品{$intervals}分钟兑换一次，上一次此商品兑换的时间是{$date_before},下次兑换时间为{$date_can}");
                return false;
            }
        }
    }

    public function getGoodBYGoodId($good_id = null, $cache = true) {
        if (!isset($good_id) || (int) $good_id < 1) {
            if (isset($this->good_id) && (int) $this->good_id) {
                $good_id = $this->good_id;
            } else {
                return false;
            }
        }
        $key = "RedeemModel_getGoodBYGoodId_{$good_id}";
        if ($return = $this->modelSetCache($key, $cache)) {
            return $return;
        }
        if ($model = $this->findByPk($good_id)) {
            Yii::app()->cache->set($key, $model, 180);
            return $model;
        }
        return false;
    }

    /**
     * App获取兑换商品列表
     * @param CDbCriteria $where
     * @param type $num
     * @param type $page
     * @return type
     */
    public function getExchangeGoodsList($where = false, $num = 20, $page = false) {

        if (is_object($where) && $where instanceof CDbCriteria) {
            $criteria = $where;
        } else if (is_array($where)) {
            $criteria = $this->where($where);
        } else if (is_string($where)) {
            $criteria = new CDbCriteria();
            $criteria->addCondition($where);
        } else {
            $criteria = new CDbCriteria();
        }
        //排序
        $criteria->order = "listorder desc,integral asc";
        //是否分页
        if ($page !== false && $num > 0) {
            $count = $this->count($criteria);
            $pager = new CPagination($count);
            $pager->pageSize = $num;
            //设置当前分页号
            $pager->setCurrentPage($page - 1 < 0 ? 0 : $page - 1);
            $pager->applyLimit($criteria);
        } else if ($num > 0) {
            //数量
            $criteria->limit = $num;
        }
        //缓存获取
        $dataList = $this->findAll($criteria);
        $return = $this->appExchangeList($dataList);
        if ($page !== false && $num > 0) {
            $return = array($return, $pager);
        }
        return $return;
    }

    /**
     * 获取积分兑换商品列表字段整理
     * @param type $data
     * @return boolean
     */
    protected function appExchangeList($data) {
        if (empty($data)) {
            return false;
        }
        $return = array();
        foreach ($data as $k => $goods) {
            $return[$k]['id'] = $goods->id;
            $return[$k]['title'] = $goods->title;
            $return[$k]['url'] = $goods->url;
            $return[$k]['img'] = $goods->thumb;
            $return[$k]['worth'] = $goods->worth;
            $return[$k]['integral'] = $goods->integral;
            $return[$k]['exchange_start_time'] = $goods->exchange_start_time;
            $return[$k]['start_time'] = $goods->start_time;
            $return[$k]['end_time'] = $goods->end_time;
            $return[$k]['add_time'] = $goods->add_time;
            $return[$k]['exchangetimes'] = "限量:" . $goods->quantum . "件";
            $sum = $goods->quantum - RedeemRecordsModel::model()->getRedeemSum($goods->id);          
            if($sum>0){
                $Saleout = 1;
            }
            else{
                $Saleout = 0;
            }
            $return[$k]['saleout'] = $Saleout;
            $return[$k]['leftnumbers'] = "还剩" . $sum . "件";
            $return[$k]['allowtimes'] = $goods->frequency;
            $return[$k]['product_id'] = $goods->product_id;
            $return[$k]['goods_brief'] = $goods->introduction;
            $return[$k]['percentage'] = $goods->commission;
            $return[$k]['intervaltime'] = $goods->scoregood_intervals;
            $return[$k]['start_time'] = $goods->start_time;
            $return[$k]['end_time'] = $goods->end_time;
        }
        return $return;
    }

    /*
     * 根据id数组 查询goods表
     * 
     */

    public function getGoodsbyid($ids_array) {
        $num = Yii::app()->params->page_size['sault_index'];
        $order = "default";
        $where = array(
            'goods_id' => array('IN', $ids_array),
        );
        $criteria = $this->where($where);
        $criteria->order = 'start_time DESC ,listorder DESC';
        $dataList = $this->findAll($criteria);
        foreach ($dataList as $rs) {
            $return[$rs->goods_id] = self::convertGood($rs, $cats);
        }

        $return = $this->orderRandomForStartTime($return);
        return $return;
        //return $this->getGoodsList($where, $num, $page, $order, false, $cacheKey);
    }

    public static function getCustomBlockGood($blcok_id = 0, $num = 8) {
        $return = array();
        if ($blcok_id == 0 || $num == 0) {
            return $return;
        }
        $time = $_SERVER["REQUEST_TIME"];
        $max_start_time = strtotime(date('Y-m-d', time())) + 86400 * 7;
        $criteria = new CDbCriteria();
        $criteria->addCondition("level = :level and status = 1 and start_time < :max_st_time and end_time > :end_time");
        $criteria->order = 'listorder DESC,start_time ASC,promo_price ASC';
        $criteria->limit = $num;
        $criteria->params = array(
            ':level' => $blcok_id,
            ':max_st_time' => $max_start_time,
            ':end_time' => $time,
        );
        $return = self::getGoodList($criteria);
        return $return;
    }

    public function getLabelForList($label = 0, $uid = '')
    {
        $uid = empty($uid) ? yii::app()->user->uid : (int)$uid;
        switch ($label) 
        {
            case 0://待审核
                $this->status = RedeemModel::STATUS_NOT;
                break;
            case 1://待审核
                $this->status = RedeemModel::STATUS_APPROVE;
                break;
            case 2://待审核
                $this->status = RedeemModel::STATUS_REJECT;
                break;
            case 3://待审核
                $this->status = RedeemModel::STATUS_CANCEL;
                break;
            case 4://待审核
                $this->pay_status = RedeemModel::PAY_STATUS_NOT;
                break;
            case 5://待审核
                $this->pay_status = RedeemModel::PAY_STATUS_HAS;
                break;
            case 6://待审核
                $this->pay_status = RedeemModel::PAY_STATUS_REFUND_HAS;
                break;            
            default:
                $this->status = RedeemModel::STATUS_NOT;
                break;
        }
        $key = "RedeemModel_getCount_{$label}";
        $mixCache = yii::app()->cache->get($key);
        if(!empty($mixCache))
        {
            return $mixCache;
        }
        //获取各种标签的数据，只执行一次SQL语句
        $objDatas = self::model()->findAll(array('select' => 'id,status,pay_status', 'condition' => "uid = $uid"));
        //统计各种总共有多少数据
        $arrCount = array(0,0,0,0,0,0,0);
        foreach($objDatas as $objData)
        {
            switch($objData->status){
                case RedeemModel::STATUS_NOT:
                    $arrCount[0]++;
                break;
                case RedeemModel::STATUS_APPROVE:
                    $arrCount[1]++;
                break;
                case RedeemModel::STATUS_REJECT:
                    $arrCount[2]++;
                break;
                case RedeemModel::STATUS_CANCEL:
                    $arrCount[3]++;
                break;
            }
            switch($objData->pay_status){
                case RedeemModel::PAY_STATUS_NOT:
                    $arrCount[4]++;
                break;
                case RedeemModel::PAY_STATUS_HAS:
                    $arrCount[5]++;
                break;
                case RedeemModel::PAY_STATUS_REFUND_HAS:
                    $arrCount[6]++;
                break;
            }
        }
        yii::app()->cache->set($key, $arrCount, 300);
        return $arrCount;
    }

}
